<template>
  <div class="login-container d-center">
    <el-card header="请先登录" class="login-card">
      <el-form @submit.native.prevent="login" label-width="60px">
        <el-form-item label="用户名">
          <el-input v-model.number="form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" show-password v-model="form.pwd"></el-input>
        </el-form-item>
        <div class="d-flex space-between mb-2">
          <span><el-checkbox v-model="checked">记住密码</el-checkbox></span>
        </div>
        <el-button class="w100" type="primary" native-type="submit">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import md5 from "md5";
import Cookies from "js-cookie";
export default {
  data() {
    return {
      checked: true,
      form: {
        name: "",
        pwd: "",
      },
    };
  },
  mounted() {
    this.getCookies();
  },
  methods: {
    getCookies() {
      if (Cookies.get("name")) {
        this.$set(this.form, "name", Cookies.get("name"));
        this.$set(this.form, "pwd", Cookies.get("pw"));
      }
    },
    setCookies() {
      if (this.checked) {
        if (!Cookies.get("name")) {
          // 记住密码有效期为 3 天
          Cookies.set("name", this.form.name, { expires: 3 });
          Cookies.set("pw", this.form.pwd, { expires: 3 });
        }
      }
    },
    async login() {
      let pwd = md5(this.form.pwd);
      let opt = this.form;
      const formData = new FormData();
      formData.append("name", opt.name);
      formData.append("pwd", pwd);
      const { data: res } = await this.$http.post("login", formData);
      // console.log(res, "登录返回");
      if (res.code != "0") return this.$message.error(res.msg);

      if (res.data.user_type == 0) {
        // 进入管理员界面
        this.setCookies();
        res.data.pwd = this.form.pwd;
        res.data.breadList = ["商品审核", "等待审核"];
        this.$store.commit("Login", res.data);
        this.$router.push("/productCheck/wait");
      } else {
        // 进入商家界面
        this.setCookies();
        res.data.pwd = this.form.pwd;
        res.data.breadList = ["订单管理", "待受理"];
        this.$store.commit("Login", res.data);
        this.$router.push("/orders/waitAccept");
      }
      this.$message.success("登录成功");
    },
  },
};
</script>

<style lang="scss">
.login-container {
  background-color: #f9f9f9;
  width: 100%;
  min-height: 688px;
  height: 100vh;
  overflow: hidden;
  .login-card {
    margin-bottom: 150px;
  }
}
</style>
